from django import forms
from django.db import models
from django.db.models import Min, Max
from django.forms import ModelForm
from .models import Car, Cargo, Location
from django.core.validators import MinValueValidator, MaxValueValidator


class CargoForm(forms.ModelForm):

    pick_up = forms.IntegerField(label='Место отправления, индекс ', required=False, disabled=False)
    deliver = forms.IntegerField(label='Место доставки, индекс ', required=False, disabled=False)
    cargo_weight = forms.IntegerField(label='Вес ', required=False, min_value=1, max_value=1000)

    class Meta:
        model = Cargo
        fields = ['pick_up', 'deliver','cargo_weight', 'description']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        zipcode_info = Location.objects.aggregate(Min('zipcode'), Max('zipcode'))
        min_zipcode = zipcode_info['zipcode__min']
        max_zipcode = zipcode_info['zipcode__max']
        self.fields['pick_up'].widget.attrs['min'] = min_zipcode
        self.fields['pick_up'].widget.attrs['max'] = max_zipcode
        self.fields['deliver'].widget.attrs['min'] = min_zipcode
        self.fields['deliver'].widget.attrs['max'] = max_zipcode


class CargoEditForm(forms.ModelForm):
    cargo_weight = forms.IntegerField(label='Вес', required=False, min_value=1, max_value=1000,)

    class Meta:
        model = Cargo
        fields = ['pick_up_location', 'deliver_location', 'cargo_weight', 'description']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['pick_up_location'].disabled = True
        self.fields['deliver_location'].disabled = True


class CarModelForm(ModelForm):
    zipcode = forms.IntegerField(label='Zipcode', required=False, disabled=True)

    class Meta:
        model = Car
        fields = ['unique_car_number', 'current_location', 'payload_type']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        print(self.fields)
        if self.instance.current_location:
            self.fields['zipcode'].initial = self.instance.current_location.zipcode
        self.fields['unique_car_number'].disabled = True
        self.fields['current_location'].disabled = True
        self.fields['zipcode'].disabled = False
        self.fields['payload_type'].disabled = True

